package com.hzw.saas.common.quartz.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzw.saas.common.quartz.config.ScheduleManager;
import com.hzw.saas.common.quartz.enums.ScheduleStatus;
import com.hzw.saas.common.quartz.mapper.ScheduleJobMapper;
import com.hzw.saas.common.quartz.model.ScheduleJob;
import com.hzw.saas.common.quartz.service.IScheduleJobService;
import org.quartz.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class ScheduleJobServiceImpl extends ServiceImpl<ScheduleJobMapper, ScheduleJob> implements IScheduleJobService {

	private final ScheduleJobMapper scheduleJobMapper;
	private final ScheduleManager scheduleManager;
	/**
	 * 项目启动时，初始化定时器
	 */
	@PostConstruct
	public void init(){
	    // 获取系统标示
        this.listBySystemProp("system.mark").forEach(scheduleJob -> {
			CronTrigger trigger = scheduleManager.getCronTrigger(scheduleJob);
            // 如果定时任务不存在，则创建定时任务
			if (trigger == null) {
				scheduleManager.createScheduleJob(scheduleJob);
			} else if (ScheduleStatus.NORMAL.getType().equals(scheduleJob.getStatus())) {
				scheduleManager.resumeJob(scheduleJob);
			} else if (ScheduleStatus.PAUSE.getType().equals(scheduleJob.getStatus())) {
				scheduleManager.pauseJob(scheduleJob);
			}
		});
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveAndStart(ScheduleJob scheduleJob) {
		scheduleJob.setCreateTime(new Date());
		scheduleJob.setStatus(ScheduleStatus.NORMAL.getType());
		scheduleJobMapper.insert(scheduleJob);

        scheduleManager.createScheduleJob(scheduleJob);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateScheduleJob(ScheduleJob scheduleJob) {
        String params = scheduleJob.getParams();

        if(StringUtil.isBlank(params)) {
            ScheduleJob byId = this.getById(scheduleJob.getJobId());
            if(byId != null) {
                scheduleJob.setParams(byId.getParams());
            }
        }

        scheduleManager.updateScheduleJob(scheduleJob);
		scheduleJobMapper.updateById(scheduleJob);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void deleteBatch(Long[] jobIds) {

		List<Long> ids = Arrays.asList(jobIds);
		this.listByIds(ids).forEach(scheduleJob -> {
			scheduleManager.deleteScheduleJob(scheduleJob);
		});
		scheduleJobMapper.deleteBatchIds(ids);
	}

	@Override
	public int updateBatch(Long[] jobIds, int status) {
		return scheduleJobMapper.updateBatch(jobIds,status);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void run(Long[] jobIds) {
    	for(Long jobId : jobIds){
    		scheduleManager.run(scheduleJobMapper.selectById(jobId));
    	}
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void pause(Long[] jobIds) {
		this.listByIds(Arrays.asList(jobIds)).forEach(scheduleJob -> {
			scheduleManager.pauseJob(scheduleJob);
		});

    	updateBatch(jobIds, ScheduleStatus.PAUSE.getType());
    }

	@Override
	@Transactional(rollbackFor = Exception.class)
    public void resume(Long[] jobIds) {
		this.listByIds(Arrays.asList(jobIds)).forEach(scheduleJob -> {
			scheduleManager.resumeJob(scheduleJob);
		});

    	updateBatch(jobIds, ScheduleStatus.NORMAL.getType());
    }

    @Override
    public List<ScheduleJob> listBySystemProp(String systemKey) {
	    if(Objects.isNull(systemKey)) return list();

        // 获取系统标示
        String systemMark = System.getProperty(systemKey, "");
        if("ALL".equalsIgnoreCase(systemMark)) return list();

        return this.list().stream().filter(scheduleJob -> {
            if(!Objects.equals(systemMark, scheduleJob.getSystemMark())) {
                log.info("filter: jobId --> {}", scheduleJob.getJobId());
                return false;
            }
            return true;
        }).collect(Collectors.toList());
    }
}
